/*
 *   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.asiainfo.redis.service.clusterhandler;

import com.asiainfo.redis.entity.ClusterNode;
import com.asiainfo.redis.repository.ClusterNodeRepository;
import org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.util.Assert;

/**
 * @version v 1.0 on 2016/5/19 18:13
 * @auther william.xu
 */
public class MigrateSlots {

    private RedisClusterHandler redisClusterHandler;
    private ClusterNodeRepository clusterNodeRepository;

    private Long fromNodeId;
    private Long toNodeId;
    private Integer slotsNum;

    public MigrateSlots(final Long fromNodeId, final Long toNodeId, final Integer slotsNum, RedisClusterHandler
            redisClusterHandler, ClusterNodeRepository clusterNodeRepository){
        this.fromNodeId = fromNodeId;
        this.toNodeId = toNodeId;
        this.slotsNum = slotsNum;
        this.redisClusterHandler = redisClusterHandler;
        this.clusterNodeRepository = clusterNodeRepository;
    }

    public Object doInRedisCluster(RedisClusterConnection connection) throws Exception {
        redisClusterHandler.checkClusterNodes(connection);
        ClusterNode fromNode = clusterNodeRepository.findOne(fromNodeId);
        Assert.notNull(fromNode, "找不到源节点,id=" + fromNodeId);
        ClusterNode toNode = clusterNodeRepository.findOne(toNodeId);
        Assert.notNull(toNode, "找不到目标节点,id=" + toNode);

        RedisClusterNode fromRedisClusterNode = new RedisClusterNode(fromNode.getIp(), fromNode.getPort());
        RedisClusterNode toRedisClusterNode = new RedisClusterNode(toNode.getIp(), toNode.getPort());
        RedisClusterNode srcNode = redisClusterHandler.lookupNode(fromRedisClusterNode, connection);
        int[] slots = srcNode.getSlotRange().getSlotsArray();
        int actualNum = slotsNum;
        if (slotsNum > slots.length) {
            actualNum = slots.length;
        }
        for (int i = 0; i < actualNum; i++) {
            redisClusterHandler.migrateSlot(slots[i], fromRedisClusterNode, toRedisClusterNode, connection);
        }
        return null;
    }
}
